import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:raze/artifacts/helper_function.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:raze/artifacts/auth_portal_dialog.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/lore/chronicle/community_chronicle.dart';
import 'package:raze/lore/chronicle/diary_chronicle.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 发布页面
class PublishRealms extends StatefulWidget {
  const PublishRealms({super.key});

  @override
  State<PublishRealms> createState() => _PublishRealmsState();
}

class _PublishRealmsState extends State<PublishRealms> {
  final TextEditingController _detailController = TextEditingController();

  // 保存发布类型（community 或 diary）
  late final String _publishType;

  // 选中的媒体文件路径
  String? _mediaPath;
  // 视频封面图路径（仅视频需要）
  String? _coverImagePath;
  // 内容类型（image 或 video）
  String? _contentType;

  @override
  void initState() {
    super.initState();
    // 从路由参数获取发布类型
    _publishType = Get.parameters['type'] ?? 'community';
  }

  @override
  void dispose() {
    _detailController.dispose();
    super.dispose();
  }

  /// 选择媒体资源（图片或视频）
  Future<void> _selectMedia() async {
    try {
      // 使用 wechat_assets_picker 选择资源
      final List<AssetEntity>? selectedAssets = await AssetPicker.pickAssets(
        Get.context!,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.common,
          specialItemPosition: SpecialItemPosition.none,
        ),
      );

      if (selectedAssets == null || selectedAssets.isEmpty) {
        return;
      }

      final asset = selectedAssets.first;

      // 获取应用文档目录
      final appDocDir = await getApplicationDocumentsDirectory();
      final mediaDir = Directory('${appDocDir.path}/media');
      if (!await mediaDir.exists()) {
        await mediaDir.create(recursive: true);
      }

      if (asset.type == AssetType.video) {
        // 视频类型
        _contentType = 'video';

        // 获取视频文件
        final videoFile = await asset.file;
        if (videoFile == null) {
          NotifierGlimmer.revealInfo('Failed to load video file');
          return;
        }

        // 复制视频到本地目录
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        final videoFileName = 'video_$timestamp.mp4';
        final videoPath = '${mediaDir.path}/$videoFileName';
        final copiedVideo = await videoFile.copy(videoPath);

        // 生成视频缩略图
        final thumbnailPath = await VideoThumbnail.thumbnailFile(
          video: copiedVideo.path,
          thumbnailPath: mediaDir.path,
          imageFormat: ImageFormat.PNG,
          maxWidth: 500,
          quality: 75,
        );

        setState(() {
          _mediaPath = copiedVideo.path;
          _coverImagePath = thumbnailPath;
        });
      } else {
        // 图片类型
        _contentType = 'image';

        // 获取图片文件
        final imageFile = await asset.originFile;
        if (imageFile == null) {
          NotifierGlimmer.revealInfo('Failed to load image file');
          return;
        }

        // 复制图片到本地目录
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        // 根据原始文件名获取扩展名
        final originalName = await asset.title;
        final extension = originalName?.split('.').last ?? 'png';
        final imageFileName = 'image_$timestamp.$extension';
        final imagePath = '${mediaDir.path}/$imageFileName';
        await imageFile.copy(imagePath);

        setState(() {
          _mediaPath = imagePath;
          _coverImagePath = null;
        });
      }
    } catch (e) {
      NotifierGlimmer.revealInfo('Failed to select media: $e');
    }
  }

  /// 发布内容
  void _publishContent() {
    final userChronicle = Get.find<UserChronicle>();

    // 检查登录状态
    if (!userChronicle.isLoggedIn) {
      AuthPortalDialog.revealAuthPortal();
      return;
    }

    final currentUser = userChronicle.currentUser;
    if (currentUser == null) {
      AuthPortalDialog.revealAuthPortal();
      return;
    }

    // 验证输入
    if (_mediaPath == null) {
      NotifierGlimmer.revealInfo('Please select an image or video');
      return;
    }

    final detail = _detailController.text.trim();
    if (detail.isEmpty) {
      NotifierGlimmer.revealInfo('Please enter content details');
      return;
    }

    try {
      if (_publishType == 'community') {
        // 发布社区帖子
        final communityChronicle = Get.find<CommunityChronicle>();
        communityChronicle.publishCommunity(
          userId: currentUser.id,
          contentType: _contentType!,
          media: _mediaPath!,
          coverImage: _coverImagePath,
          detail: detail,
        );
        NotifierGlimmer.revealInfo('Community post published successfully!');
      } else if (_publishType == 'diary') {
        // 发布日志
        final diaryChronicle = Get.find<DiaryChronicle>();
        diaryChronicle.publishDiary(
          userId: currentUser.id,
          contentType: _contentType!,
          media: _mediaPath!,
          coverImage: _coverImagePath,
          detail: detail,
        );
        NotifierGlimmer.revealInfo('Diary published successfully!');
      }

      // 返回上一页
      Get.back();
    } catch (e) {
      NotifierGlimmer.revealInfo('Failed to publish: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _constructTopNavigationBar(),

              // 主要内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 详情输入区域（包含媒体选择）
                        _constructDetailInputArea(),

                        12.h.boxHeight,

                        // 提示文本
                        Center(
                          child:
                              Text(
                                    'Only One File, Photo Or Video Can Be Uploaded For Each Release',
                                  )
                                  .applyTypeSize(12.sp)
                                  .applyTypeColor(
                                    RazeConstants.black.withOpacity(0.6),
                                  )
                                  .applyNotoSans(),
                        ),
                      ],
                    ),
                  ),
                ),
              ),

              // 底部发布按钮和EULA链接
              _constructBottomSection(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _constructTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  borderRadius: BorderRadius.circular(8.r),
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                ),
                child: Icon(
                  Icons.chevron_left_rounded,
                  size: 24.sp,
                  color: RazeConstants.black,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(onTap: () => Get.back()),

          Expanded(
            child: Center(
              child: Text('Share')
                  .applyTypeSize(20.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyBagelFatOne(weight: FontWeight.w400),
            ),
          ),

          // 占位（保持返回按钮居中）
          30.w.boxWidth,
        ],
      ),
    );
  }

  /// 构建详情输入区域（包含媒体选择）
  Widget _constructDetailInputArea() {
    return Container(
      constraints: BoxConstraints(minHeight: 231.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: RazeConstants.white,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: RazeConstants.black, width: 1.w),
      ),
      child: Stack(
        children: [
          // 文本输入框
          Padding(
            padding: EdgeInsets.only(bottom: 90.h), // 为底部媒体按钮预留空间
            child: TextField(
              controller: _detailController,
              maxLines: null,
              minLines: 10,
              textInputAction: TextInputAction.done,
              decoration: InputDecoration(
                hintText: 'Please Write Down Your Observations For Today.',
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                  color: RazeConstants.black.withOpacity(0.5),
                  fontFamily: 'NotoSans',
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.zero,
              ),
              style: TextStyle(
                fontSize: 14.sp,
                color: RazeConstants.black,
                fontFamily: 'NotoSans',
              ),
            ),
          ),

          // 媒体选择区域（底部左侧，浮动在输入框上）
          Positioned(
            bottom: 0.w,
            child: GestureDetector(
              onTap: _selectMedia,
              child: Container(
                width: 80.w,
                height: 80.w,
                decoration: BoxDecoration(
                  color: RazeConstants.white,
                  borderRadius: BorderRadius.circular(4.r),
                  border: Border.all(
                    color: RazeConstants.black.withOpacity(0.3),
                    width: 1.w,
                  ),
                ),
                child:
                    _mediaPath == null
                        ? Icon(
                          Icons.add_photo_alternate_outlined,
                          size: 32.sp,
                          color: RazeConstants.black.withOpacity(0.5),
                        )
                        : ClipRRect(
                          borderRadius: BorderRadius.circular(4.r),
                          child:
                              _contentType == 'video'
                                  ? Stack(
                                    fit: StackFit.expand,
                                    children: [
                                      // 显示视频封面
                                      Image.file(
                                        File(_coverImagePath!),
                                        fit: BoxFit.cover,
                                      ),
                                      // 播放图标
                                      Center(
                                        child: Container(
                                          width: 24.w,
                                          height: 24.w,
                                          decoration: BoxDecoration(
                                            color: RazeConstants.black
                                                .withOpacity(0.6),
                                            shape: BoxShape.circle,
                                          ),
                                          child: Icon(
                                            Icons.play_arrow_rounded,
                                            size: 16.sp,
                                            color: RazeConstants.white,
                                          ),
                                        ),
                                      ),
                                    ],
                                  )
                                  : Image.file(
                                    File(_mediaPath!),
                                    fit: BoxFit.cover,
                                  ),
                        ),
              ).withRightBottomShadow(thickness: 1),
            ),
          ),
        ],
      ),
    ).withRightBottomShadow(thickness: 2);
  }

  /// 构建底部区域（发布按钮和EULA链接）
  Widget _constructBottomSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 发布按钮
          Container(
                width: double.infinity,
                height: 50.h,
                decoration: BoxDecoration(
                  color: RazeConstants.blue,
                  borderRadius: BorderRadius.circular(12.r),
                  border: Border.all(color: RazeConstants.black, width: 2.w),
                ),
                alignment: Alignment.center,
                child: Text('Publish')
                    .applyTypeSize(18.sp)
                    .applyTypeColor(RazeConstants.white)
                    .applyBagelFatOne(
                      weight: FontWeight.w600,
                      shadows: [
                        Shadow(
                          offset: Offset(1.w, 1.w),
                          blurRadius: 0,
                          color: RazeConstants.black,
                        ),
                        Shadow(
                          offset: Offset(-1.w, -1.w),
                          blurRadius: 0,
                          color: RazeConstants.black,
                        ),
                        Shadow(
                          offset: Offset(1.w, -1.w),
                          blurRadius: 0,
                          color: RazeConstants.black,
                        ),
                        Shadow(
                          offset: Offset(-1.w, 1.w),
                          blurRadius: 0,
                          color: RazeConstants.black,
                        ),
                      ],
                    ),
              )
              .withRightBottomShadow(thickness: 1.5)
              .withTouchResonance(onTap: _publishContent),

          12.h.boxHeight,

          // EULA链接
          GestureDetector(
            onTap: () {
              HelperFunction.launchUrl(RazeConstants.eulaUrl);
            },
            child: Text(
              'EULA',
              style: TextStyle(
                fontSize: 12.sp,
                color: RazeConstants.black,
                fontFamily: 'NotoSans',
                decoration: TextDecoration.underline,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
